<?php
/**
 * @author Rootkit
 * @version v1.0
 * @description 
 * @date 2015-3-4
 */
namespace Home\Model;

use Think\Model;
class MemberPublicModel extends Model{
	
	/**
	 * 获取公众号信息
	 * @param unknown $uid 用户ID
	 * @param string $page 分页
	 * @param string $row 行数
	 * @return unknown
	 */
	function getPublicInfo($uid, $page = '', $row = ''){
		$map['uid'] = $uid;
		if (isset($page)) {
			$data = $this->where($map)->order('id DESC')->page($page, $row)->select();
		} else {
			$data = $this->where($map)->order('id DESC')->select();
		}
		
		foreach ( $data as &$vo ) {
			if (! empty ( $vo ['headface_url'] ))
				$vo ['headface_url'] = '<img src="' . $vo ['headface_url'] . '" style="width:50px;height:50px;" />';
			else
				$vo ['headface_url'] = '<img src="http://www.bftest.com/uploads/image/20150228/20150228173630_37358.jpg" style="width:50px;height:50px;" />';
		}
		return $data;
	}
	
	function getPublicCount($uid){
		$map['uid'] = $uid;
		return $this->where ($map)->count ();
	}
	
	/**
	 * 添加公众号
	 * @return Ambigous <\Think\mixed, boolean, string, unknown>
	 */
	function addPublic(){
		$data = array(
				'uid' => get_mid(),
				'public_name'	=> I('plc_name'),
				'public_id'		=> I('plc_sourceid'),
				'wechat'		=> I('wechat_id'),
				'interface_url' => $this->createInterface(),
				'headface_url'	=> I('avatar_url'),
				'token'			=> $this->createToken(),
		);
		return $this->add($data);
	}
	
	/**
	 * 更新公众号信息
	 * @param type $id
	 * @return type
	 */
	function udtPublic($id){
		$map['id'] = $id;
		$data = array(
			'public_name'	=> I('plc_name'),
			'wechat'		=> I('wechat_id'),
			'headface_url'	=> I('avatar_url')
		);
		return $this->where($map)->save($data);
	}
	
	/**
	 * 检测public_id是否存在
	 * @param type $publicId
	 * @return type
	 */
	function chkPublicId($publicId){
		$map['public_id'] = $publicId;
		return $this->where($map)->find();
	}


	/**
	 * 由ID获取公众号信息
	 * @param type $id
	 * @return type 
	 */
	function getPublicById($id){
		$map['id'] = $id;
		return $this->where($map)->find();
	}
	
	/**
	 * 生成8位数TOKEN
	 * @return string
	 */
	function createToken(){
		return 'mk'.$this->getRand(6);
	}

	
	/**
	 * 生成接口字符串
	 * @return string
	 */
	function createInterface(){
		return  $this->getRand(6).time();
	}
	
	/**
	 * 获取随机字符
	 * @param unknown $count 位数
	 * @return string
	 */
	function getRand($count){
		$chars		= 'abcdefghijklmnopqrstuvwxyz';
		$len		= strlen($chars);
		$randStr	= '';
		for ($i = 0; $i < $count; $i++){
			$randStr .= $chars[rand(0, $len-1)];
		}
		return $randStr;
	}
	
	/**
	 * 通过Interface_url获取token
	 * @param unknown $interface
	 * @return Ambigous <\Think\mixed, NULL, mixed, multitype:Ambigous <unknown, string> unknown , unknown>
	 */
	function getTokenByInterface($interface){
		$map['interface_url'] = $interface;
		return $this->where($map)->getField('token');
	}
	
	function getTokenById($id){
		$map['id'] = $id;
		return $this->where($map)->getField('token');
	}
}